package com.rjet.javacallpython;

import org.python.util.PythonInterpreter;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * @Author:ethan
 * @Date: 2023/12/11  14:00
 * @Version 1.0.1
 */
public class JavaCallPythonLib {


    public static String callTest(){

        String result = "";
        try {
            //这个方法是类似隐形开启了命令执行器，输入指令执行python脚本
            //python指令位置 + " " + python脚本位置 必须绝对路径
            String compiler = "G:\\python\\workspace\\venv\\Scripts\\python.exe";
            String program = "G:\\rjetwork\\code\\Java\\javacallpython\\src\\main\\java\\com\\rjet\\javacallpython\\qrcode_location.py";

            String[] cmds = {compiler, program, "11", "2"};
            Process process = Runtime.getRuntime().exec(cmds);
            //这种方式获取返回值的方式是需要用python打印输出，然后java去获取命令行的输出，在java返回
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            result = input.readLine();//中文的话这里可能会有乱码，可以尝试转一下不过问题不大
            result = new String(result.getBytes("iso8859-1"),"utf-8");
            input.close();
            ir.close();
            int re = process.waitFor();
            System.out.println(" result = " + result);

        } catch (IOException | InterruptedException e) {
            System.out.println("调用python脚本并读取结果时出错：" + e.getMessage());
        }
        return result;

    }

    public static void main(String[] args) throws Exception{

        callTest();
    }
}
